package com.jwj.testback.backups.service.impl;


import com.jwj.testback.backups.pojo.MysqlBackups;
import com.jwj.testback.backups.dao.MysqlBackupsMapper;
import com.jwj.testback.backups.service.MysqlBackupsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.jwj.testback.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.FileUtil;
import org.springframework.transaction.TransactionDefinition;

import javax.annotation.Resource;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.util.List;

/**
 * <p>
 * MySQL数据备份表 服务实现类
 * </p>
 *
 * @author JWJ
 * @since 2021-12-07
 */
@Service
public class MysqlBackupsServiceImpl extends ServiceImpl<MysqlBackupsMapper, MysqlBackups> implements MysqlBackupsService {

//    @Resource
//    private MysqlBackupsMapper backupsMapper;

//    public static final String Ip = "120.78.234.226";

    @Resource
    DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    TransactionDefinition transactionDefinition;

//    //删除全部数据
//    @Override
//    public Boolean delSure(String table, String mainId) {
//        int count = baseMapper.count(table);
//        int ceil = (int) Math.ceil(count / 1000.0);
//        for (int i = 1; i <= ceil; i++) {
//            baseMapper.delSure(table, mainId);
//        }
//        return true;
//    }

//    //显示所有库
//    @Override
//    public List<String> showDateBase() {
//        List<String> list = baseMapper.showDateBase();
//        return list;
//    }

    //显示所有表
    @Override
//    @DataSource
    public List<String> showTables(String databaseName,String table) {
        List<String> list = baseMapper.showTables();
        return list;
    }

    //备份所有表
    @Override
    public String mysqlBackups(String Ip,String filePath, String database_name,String table_name,String mysqlFileName, String userName, String passWord) {
        //获取桌面路径
        FileSystemView fsv = FileSystemView.getFileSystemView();
        File com=fsv.getHomeDirectory();
        //这就是桌面路径
        String path = com.getPath()+"/";

        //数据库文件名
//        StringBuilder mysqlFileName = new StringBuilder()
//                .append(database_name)
//                .append("_")
//                .append(DateUtil.format(new Date(), "yyyy-MM-dd-HH-mm-ss"))
//                .append(Constants.FILE_SUFFIX);
//        System.out.println("sql文件名字："+mysqlFileName);

        MysqlBackups smb = new MysqlBackups();
        StringBuilder cmd = new StringBuilder();

        if (filePath!=null){
            // 判断文件是否保存成功
            if (!FileUtil.exist(filePath)) {
                FileUtil.mkdir(filePath);
//                return "暂无此路径，已自动为您创建，请再次点击确定";
            }

            // 备份单表命令
            cmd.append("mysqldump ")
                .append("--no-defaults ")
                .append("-h")
                .append(Ip)
                .append(" -u")
                .append(userName)
                .append(" -p")
                .append(passWord)
                .append(" "+database_name)
                .append(" "+table_name)
                .append(" > ")
                .append(filePath)
                .append(mysqlFileName);

        }else {
            //默认被分在桌面
            cmd.append("mysqldump ")
                    .append("--no-defaults ")
                    .append("-h")
                    .append(Ip)
                    .append(" -u")
                    .append(userName)
                    .append(" -p")
                    .append(passWord)
                    .append(" "+database_name)
                    .append(" "+table_name)
                    .append(" > ")
                    .append(path)
                    .append(mysqlFileName);
        }
        //保存备份记录到数据库
        smb.setMysqlIp(Ip);
//        smb.setMysqlCmd(String.valueOf(cmd));
        smb.setDatabaseName(database_name);
        smb.setBackupsName(String.valueOf(mysqlFileName));
        smb.setOperation(0);
        smb.setStatus(1);
        smb.setCreateTime(DateTime.now());
        baseMapper.insert(smb);
        System.out.println("数据库备份命令:"+cmd);

                // 获取操作系统名称
        String osName = System.getProperty("os.name").toLowerCase();
        String[] command = new String[0];
        if (Constants.isSystem(osName)) {
        // Windows
            System.out.println("这里是window系统");
            command = new String[]{"cmd", "/c", String.valueOf(cmd)};
        } else {
//            // Linux
            System.out.println("这里是linux系统");
            command = new String[]{"/bin/sh", "-c", String.valueOf(cmd)};
        }
        // 获取Runtime实例
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(command);

            if (process.waitFor() == 0) {
                System.out.println("Mysql 数据库备份成功,备份文件名："+mysqlFileName);
                return "Mysql 数据库备份成功,备份文件名："+mysqlFileName;
            } else {
                return"网络异常，或填写数据错误，请检查后重试";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "数据库备份失败";
        }
    }

}
